package com.cwc.ueditor.service.iml;

import com.cwc.ueditor.entity.ImgFile;
import com.cwc.ueditor.mapper.ImgFileMapper;
import com.cwc.ueditor.service.FileOperationService;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author wxhntmy
 */
@Service
public class FileOperationServiceIml implements FileOperationService {

    @Resource
    private ImgFileMapper imgFileMapper;

    private final String[] imgFiles = {".png", ".jpg", ".jpeg", ".gif", ".bmp"};
    private final String[] videoFiles = {".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
            ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"};

    /**
     * 保存文件
     *
     * @param file 文件
     * @param uuid uuid
     * @return 保存成功返回true
     */
    @Override
    public boolean saveFile(MultipartFile file, String uuid) {
        try {
            File path = path(file.getContentType());
            String filename = file.getOriginalFilename();

            //获取最后一个.的位置
            int lastIndexOf = filename.lastIndexOf(".");
            //获取文件的后缀名 .jpg
            String suffix = filename.substring(lastIndexOf);

            ImgFile fileEntity = new ImgFile();
            fileEntity.setFileName(filename);
            fileEntity.setUuid(uuid);
            String storeaddress = path.getAbsolutePath();
            fileEntity.setStoreaddress(storeaddress);

            if (Arrays.asList(imgFiles).contains(suffix)){
                fileEntity.setType("img");
            }
            else if (Arrays.asList(videoFiles).contains(suffix)){
                fileEntity.setType("video");
            }
            else {
                fileEntity.setType("file");
            }

            File saveFile = new File(path, uuid);
            try {
                imgFileMapper.save(fileEntity);
                file.transferTo(saveFile);
                return true;
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件保存异常");
            return false;
        }
    }

    /**
     * 获取所有imgfile
     * @return
     */
    @Override
    public Map<String, Object> getAllImgFiles(int start, int size){

        Map<String, Object> map = new HashMap<>();
        map.put("list", imgFileMapper.getAllImgFiles(start, (start+size)));
        map.put("num", imgFileMapper.getAllImgFilesNum());

        return map;
    }

    /**
     * 获取所有file
     * @return
     */
    @Override
    public Map<String, Object> getAllFiles(int start, int size){

        Map<String, Object> map = new HashMap<>();
        map.put("list", imgFileMapper.getAllFiles(start, (start+size)));
        map.put("num", imgFileMapper.getAllFilesNum());

        return map;
    }

    /**
     * 检验文件路径是否存在
     *
     * @param type 文件类型
     * @return
     */
    @Override
    public File path(String type) {
        File path  = new File(FILE_PATH);
        if (!path.isDirectory()) {
            path.mkdir();
        }
        return path;
    }

    /**
     * 下载
     *
     * @param uuid
     * @param request
     * @param response
     */
    @Override
    public void download(String uuid, HttpServletRequest request, HttpServletResponse response) {
        ImgFile fileentity = imgFileMapper.findByUuid(uuid);
        String filename = fileentity.getFileName();
        filename = getStr(request, filename);
        File file = new File(fileentity.getStoreaddress(), uuid);
        if (file.exists()) {
            FileInputStream fis;
            try {
                fis = new FileInputStream(file);
                response.setContentType("application/x-msdownload");
                response.addHeader("Content-Disposition", "attachment; filename=" + filename);
                ServletOutputStream out = response.getOutputStream();
                byte[] buf = new byte[2048];
                int n = 0;
                while ((n = fis.read(buf)) != -1) {
                    out.write(buf, 0, n);
                }
                fis.close();
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String getStr(HttpServletRequest request, String fileName) {
        String downloadFileName = null;
        String agent = request.getHeader("USER-AGENT");
        try {
            if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
                //downloadFileName = "=?UTF-8?B?" + (new String(Base64Utils.encode(fileName.getBytes("UTF-8")))) + "?=";
                //设置字符集
                downloadFileName = "=?UTF-8?B?" + Base64Utils.encodeToString(fileName.getBytes("UTF-8")) + "?=";
            } else {
                downloadFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return downloadFileName;
    }


}
